package com.netwrok;

import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class NetworkEvents implements Runnable {



	boolean running = false;
	private ExecutorService threadPool = Executors.newCachedThreadPool();
	IoQueues queues = IoQueues.getInstance();
	Handler handler = null;


	public NetworkEvents(Handler handler) {
		this.handler = handler;
		running = true;
		Thread th = new Thread(this);
		th.start();
	}

	void finish() {
		running = false;
	}

	void writeResponse(IoSession session, ResponseMsg msg) {
		queues.addResponse(session, msg.toBytebuffer());
	}

	@Override
	public void run() {
		while (running) {
			IoEvent event = queues.getIoEvent();
			threadPool.execute(event);
		}
	}

	private void encode(IoSession session) {

	}

	void decode(IoSession session) {

		short headTag;
		short length;
		ByteBuffer buffer = session.buffer;

		while (buffer.remaining() > 0) {
			int remain = buffer.remaining();
			if (remain <= 4) {
				session.buffer.compact();
				return;
			}
			buffer.mark();
			headTag = buffer.getShort();
			if (headTag != 127) {// not valiue
				buffer.reset();
				session.buffer.compact();
				queues.addCloseSession(session, this);
				return;
			}
			length = buffer.getShort();
			if (length < 4 || length > 65535) {// length is not ok
				buffer.reset();
				session.buffer.compact();
				queues.addCloseSession(session, this);
				return;
			}
			if (remain < length) {// not enouph
				buffer.reset();
				session.buffer.compact();
				queues.addCloseSession(session, this);
				return;
			}
			byte[] dst = new byte[length - 4];
			buffer.get(dst);
			RequestMsg requestMsg = new RequestMsg(dst);
			queues.addMsg(session, requestMsg, this);
			// (new IoEvent(IoEvent.Type_Msg_Rcv, session, requestMsg,
			// this));
		}

	}

}
